package com.youi.webbg;

import com.youi.common.SessionKey;
import com.youi.manage.HttpSessionManage;
import com.youi.util.CommonInfoUtil;
import com.youi.util.JsonUtil;
import com.youi.util.ValidateCode;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 验证码
 *
 * @author erdong.Chan
 */
@Controller
public class ValidateCodeController {

    /**
     * 小程序获取sessionid
     */
    @ResponseBody
    @RequestMapping("getSessionId")
    public String getSessionId(ModelMap modelMap, HttpServletRequest request, String name) {
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        modelMap.put("sessionId", sessionId);
//		modelMap.put("phone_appid", JsonUtil.toJson(WechatUtil.phone_appid));
//		modelMap.put("phone_mch_id", JsonUtil.toJson(WechatUtil.phone_mch_id));
//		modelMap.put("phone_secret", JsonUtil.toJson(WechatUtil.phone_secret));
//		modelMap.put("wechat_appid", JsonUtil.toJson(WechatUtil.wechat_appid));
        modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
        return JsonUtil.toJson(modelMap);
    }

    /**
     * 图片验证码
     *
     * @param modelMap
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("validateCode")
    public void createValidateCode(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ValidateCode validateCode = new ValidateCode(120, 38, 4, 0);
        HttpSessionManage.setAttribute(request, SessionKey.VALIDATECODE, validateCode.getCode());
        BufferedImage bufferedImage = validateCode.getBuffImg();
        OutputStream out = response.getOutputStream();
        ImageIO.write(bufferedImage, "jpeg", out);
        out.close();
    }


    @RequestMapping("404")
    public String errot404() {
        return "error";
    }

    @RequestMapping("index")
    public String index(ModelMap modelMap, String name) {
        modelMap.put("name", name);
        return "index";
    }

    public static void main(String[] args) {
        String redirectUri = "http://www.ibranco.com/BrancoLIFE/userGetJsonInfo";
        if (redirectUri.contains("/userGetJsonInfo")) {
            redirectUri = redirectUri.replaceAll("/userGetJsonInfo", "");
        }
        System.out.println(redirectUri);
    }
}
